package com.stu.day18;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author zy
 * @date 2025/2/20 15:12
 */
public class MethodDemo {
    public static void main(String[] args) throws Exception {
//        Class<?> c = User.class;
        System.out.println(User.class.getName());
        String s = User.class.getName();
        Class<?> c = Class.forName(s);

        Method[] methods = c.getMethods();
        for (Method method : methods) {
            System.out.print(Modifier.toString(method.getModifiers()) + " ");  // 方法修饰符

            Class<?> returnType = method.getReturnType();  // 方法返回类型
            System.out.print(returnType.getSimpleName()+" ");

            System.out.print(method.getName()+" ");  // 方法名称

            Class<?>[] parameterTypes = method.getParameterTypes();  // 方法参数列表
            for (int i = 0; i < parameterTypes.length; i++) {
                System.out.print(parameterTypes[i].getSimpleName()+" ");
            }

            System.out.println();
        }

        // 反射构造方法进行全参构造
        User user = (User) c.getConstructor(Integer.class, String.class, int.class, String.class)
                .newInstance(1,"Tom",18,"male");
        System.out.println(user);

        Method method = c.getDeclaredMethod("setName", String.class);
        method.setAccessible(true);  // 设置可访问
        method.invoke(user,"Jack");  // 参数为对象,方法
        System.out.println(user);

        Method method2 = c.getDeclaredMethod("test", int.class);
        method2.setAccessible(true);
        method2.invoke(null,5);  // 静态方法参数为null,方法

    }
}
